import 'package:auntserver/app_constants.dart';
import 'package:auntserver/model/entitys.dart';
import 'package:auntserver/net_api/aunt_datas.dart';
import 'package:auntserver/router_handler/routers.dart';
import 'package:auntserver/utils/aunt_utils.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';

import '../application.dart';


enum SplashStatus {
  guide,
  banner,
  blank,
}

///启动页
class SplashScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new SplashScreenState();
  }
}

class SplashScreenState extends State<SplashScreen> {
  TimerUtil _timerUtil;
  AuntEntity _auntEntity;
  List<String> _guideList = [
    Utils.getImgPath('p1'),
    Utils.getImgPath('p2'),
    Utils.getImgPath('p3'),
  ];

  List<Widget> _bannerList = new List();
  List<Widget> __guideWidgetList = new List();
  var _status = SplashStatus.blank;

  int _timeCount = 99;
  bool _showJump = false;
  //SplashModel _splashModel;

  @override
  void initState() {
    super.initState();
    _init();
  }

  void _init() async {
    /**
     * 延时之后开始执行后续展示内容
     * 第一次进展示教程向导
     * 后续进入展示banner
     * banner来自接口数据，
     * banner数据访问失败和成功都会开始计时，计时结束进入主页
     * 教程向导不计时，到最后一页会有下一步按钮
     */
    Rx.combineLatestList([
      Rx.fromCallable(() async {
        await SpUtil.getInstance();
      }),
      Rx.timer(1, Duration(milliseconds: 1000)),
    ]).listen((_) {
      _auntEntity = SpUtil.getObj(KeyConstant.key_userInfo, (v) => AuntEntity.fromJson(v),defValue: AuntEntity());
      if (SpUtil.getBool(KeyConstant.key_guide, defValue: true) &&
          ObjectUtil.isNotEmpty(_guideList)) {
        SpUtil.putBool(KeyConstant.key_guide, false);
        _initGuide();
      } else {
        AuntData.requestWelcome().then((value) {
          setState(() {
            _showJump = true;
          });
          if (value is WelcomeEntity) {
            _initBanner(value);
          } else {
            _doCountDown();
          }
        });
      }
    });
  }

  void _initGuide() {
    _initGuideData();
    setState(() {
      _status = SplashStatus.guide;
    });
  }

  void _initBanner(WelcomeEntity welcomeEntity) {
    if(ObjectUtil.isNotEmpty(welcomeEntity)
        &&ObjectUtil.isNotEmpty(welcomeEntity.accessList)){
      _initBannerData(welcomeEntity);
      setState(() {
        _status = SplashStatus.banner;
      });
    }else{
      _doCountDown();
    }

  }

  void _initBlank() {
    setState(() {
      _status = SplashStatus.blank;
    });
  }
  void _doCountDown() {
    _timerUtil = new TimerUtil(mTotalTime: 5 * 1000);
    _timerUtil.setOnTimerTickCallback((int tick) {
      double _tick = tick / 1000;
      setState(() {
        _timeCount = _tick.toInt();
      });
      if (_tick == 0) {
        _goNext();
      }
    });
    _timerUtil.startCountDown();
  }

  void _goNext() {
    if (!ObjectUtil.isEmpty(_auntEntity.userinfo)&&!ObjectUtil.isEmptyString(_auntEntity.userinfo.accesstoken)) {
      AuntData.requestAutoLogin(_auntEntity.userinfo.accesstoken).then((value) {
        if (value is AuntEntity) {
          Provider.of<AuntEntity>(context, listen: false).updateAuntInfo(value.userinfo);
          print("去首页");
          AuntApp.router.navigateTo(context, Routes.main);
        } else {
          print("去登录页");
          AuntApp.router.navigateTo(context, Routes.chooseIdentity);
        }
      });
    } else {
      print("去登录页");
      AuntApp.router.navigateTo(context, Routes.chooseIdentity);
    }
  }

  void _initBannerData(WelcomeEntity welcomeEntity) {

    welcomeEntity.accessList.forEach((welcomeAccess) {
      _bannerList.add(Stack(
        children: [
          Image.network(
            welcomeAccess.picurl,
            fit: BoxFit.fill,
            width: double.infinity,
            height: double.infinity,
          ),
          Align(
            alignment: Alignment.topRight,
            child: GestureDetector(
              onTap: (){
                AuntApp.router.navigateTo(context, Routes.chooseIdentity);
              },
              child: FlutterLogo(
                size: 60,
              ),
            ),
          ),

        ],
      ));
    });
    welcomeEntity.accessList.forEach((welcomeAccess) {
      _bannerList.add(Stack(
        children: [
          Image.network(
            welcomeAccess.picurl,
            fit: BoxFit.fill,
            width: double.infinity,
            height: double.infinity,
          ),
          Align(
            alignment: Alignment.topRight,
            child: FlutterLogo(
              size: 20,
            ),
          ),

        ],
      ));
    });
    welcomeEntity.accessList.forEach((welcomeAccess) {
      _bannerList.add(Stack(
        children: [
          Image.network(
            welcomeAccess.picurl,
            fit: BoxFit.fill,
            width: double.infinity,
            height: double.infinity,
          ),
          Align(
            alignment: Alignment.topRight,
            child: FlutterLogo(
              size: 20,
            ),
          ),

        ],
      ));
    });
    welcomeEntity.accessList.forEach((welcomeAccess) {
      _bannerList.add(Stack(
        children: [
          Image.network(
            welcomeAccess.picurl,
            fit: BoxFit.fill,
            width: double.infinity,
            height: double.infinity,
          ),
          Align(
            alignment: Alignment.topRight,
            child: FlutterLogo(
              size: 20,
            ),
          ),

        ],
      ));
    });
  }

  void _initGuideData() {
    for (int i = 0, length = _guideList.length; i < length; i++) {
      if (i == length - 1) {
        __guideWidgetList.add(new Stack(
          children: <Widget>[
            new Image.asset(
              _guideList[i],
              fit: BoxFit.fill,
              width: double.infinity,
              height: double.infinity,
            ),
            new Align(
              alignment: Alignment.topRight,
              child: new Container(
                margin: EdgeInsets.only(bottom: 160.0),
                child: new InkWell(
                  onTap: () {
                    EasyLoading.show(status: 'loading...');
                  },
                  child: new CircleAvatar(
                    radius: 48.0,
                    backgroundColor: Colors.indigoAccent,
                    child: new Padding(
                      padding: EdgeInsets.all(2.0),
                      child: new Text(
                        '立即体验',
                        textAlign: TextAlign.center,
                        style: TextStyle(color: Colors.white, fontSize: 16.0),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ));
      } else {
        __guideWidgetList.add(new Image.asset(
          _guideList[i],
          fit: BoxFit.fill,
          width: double.infinity,
          height: double.infinity,
        ));
      }
    }
  }

  // ignore: missing_return
  Widget _getStatusWidget() {
    switch (_status) {
      case SplashStatus.banner:
        return Swiper(
          itemBuilder: (BuildContext context, int index) {
            return _bannerList[index];
          },
          loop: false,
          autoplay: true,
          autoplayDelay: 2000,
          itemCount: _bannerList.length,
          //control: new SwiperControl(),//如果不填则不显示左右按钮
        );
      case SplashStatus.guide:
        return Swiper(
          itemBuilder: (BuildContext context, int index) {
            return __guideWidgetList[index];
          },
          itemCount: __guideWidgetList.length,
          //control: new SwiperControl(),//如果不填则不显示左右按钮
        );
      case SplashStatus.blank:
        return Column(
          children: [
            Container(
              child: Align(
                alignment: Alignment.topRight,
                child: Offstage(
                  offstage: !_showJump,
                  child: FlatButton(
                    shape: CircleBorder(
                      side: BorderSide()
                    ),
                    child: Text("跳过"+(_timeCount<=5?_timeCount.toString():"")),
                    onPressed: (){
                      if (_timerUtil != null) _timerUtil.cancel();
                      _goNext();
                    },
                  ),
                ),
              ),
            ),
            Expanded(
              child: Align(
                alignment: Alignment.bottomCenter,
                child: FlutterLogo(
                  size: ScreenUtil.getInstance().getWidth(100),
                ),
              ),
            ),
          ],
        );
    }
  }



  Widget _buildSplashBg() {
    return new Image.asset(
      Utils.getImgPath('p1'),
      width: double.infinity,
      fit: BoxFit.fill,
      height: double.infinity,
    );
  }

  @override
  Widget build(BuildContext context) {
      return SafeArea(child: _getStatusWidget());
  }

  @override
  void dispose() {
    super.dispose();
    if (_timerUtil != null) _timerUtil.cancel(); //记得在dispose里面把timer cancel。
  }
}
